<?php
namespace EasyPhpWeb;

class Request{
    private $strRequest;
    private $body;

    /**
     * 请求方式
     */
    public $method = "GET";

    /**
     * 
     */
    public $headers = [];

    /**
     * query 参数
     */
    private $query = [];

    public $queryStr = "";

    /**
     * 
     */
    public $uri = "";

    
    public function setStrRequest($str){
        $this->strRequest = $str;
    }

    /**
     * 查询参数
     */
    public function query($name = false){
        return $name ? $this->query[$name] : $this->query;
    }

    public function setQuery($queryArray){
        $this->query = $queryArray;
    }

    public function analysis(){
        list ($headerStr, $body) = explode("\r\n\r\n", $this->strRequest);
        $this->body = $body;

        //从头部解析出请求方式及请求地址
        $headerList = explode("\r\n", $headerStr);
        list ($method, $url, $agreement) = explode(" ", array_shift($headerList));
        $this->method = $method;

        //从地址中解析出uri和参数
        list ($uri, $queryStr) = explode("?", $url);
        $this->queryStr = $queryStr;

        parse_str($queryStr, $query);
        $this->query = $query;
        $this->uri = $uri;

        //解析uri

        foreach($headerList as $header){
            list ($key, $value) = explode(": ", $header);
            $this->headers[$key] = $value;

            switch($key){
                case "content-type" :
                    $this->body = new RequestBody($value, $this->body);
                    break;
            }
        }
    }
}